﻿var User = function () {
    var userList = function () {
        /* 表格初始化 */
        //var table = $('#tableview');
        var txtLikeName = $("#txtLikeName");
        var btnSearch = $("#btnSearch");
        var btnCreate = $("#btnCreate");
        var btnCancel = $("#btnCancel");
        var container = $("#table_content");
        var avatar = $("#avatar");
        var addUserForm = $("#addUserForm");
        var tableview = $("#tableview");
        var postData = {
            ajax: true,
            group: '',
            active: ''
        };
        var fileuoloadData = null;
        addUserForm.Items = addUserForm.find(".form-body > .form-group");

        btnCreate.message = function (response) {
            if (response.Result) {
                toastr["success"](response.Message, "创建新用户");
                xhrRequest(location.href);
                btnCancel.click();
            } else {
                toastr["error"](response.Message, "创建新用户");
            }
        };
        btnCreate.init = function () {
            this.empty().html("创建用户");
            this.removeAttr("disabled");
        };

        var btnResetPassword = $("#btnResetPassword");
        btnResetPassword.init = function () {
            this.empty().html("重置密码");
            this.removeAttr("disabled");
        };
        btnResetPassword.message = function (response, uidobjs) {
            if (response.Result) {
                var uidList = response.Data;
                var errCount = 0;

                if (uidList) {
                    uidobjs.each(function () {
                        for (var i in uidList) {
                            if (uidList[i] == this.value) {
                                if (!this.checked) this.click();
                                errCount++;
                                return;
                            }
                        }

                        if (this.checked) this.click();
                    });
                }

                if (errCount > 0) {
                    toastr["warning"]("部分用户密码发送失败", "用户密码重置");
                } else {
                    toastr["success"](response.Message, "用户密码重置");
                }

                $("#btnResetCancel").click();
            } else {
                toastr["error"](response.Message, "用户密码重置");
            }
        };

        avatar.fileupload({
            dataType: "json",
            url: addUserForm.attr("action"),
            autoUpload: false,
            maxFileSize: 1000000,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            add: function (e, data) {
                fileuoloadData = data;
            },
            done: function (e, data) {
                btnCreate.message(data.result);
                btnCreate.init();
            },
            fail: function () {
                toastr["error"]("您没有权限或是程序碰到问题没有正确执行！", "创建新用户");
                btnCreate.init();
            }
        });

        var upImgPreview = avatar.uploadImagePreview({
            previewContainerID: 'image-preview'
        });

        toastr.options = {
            "closeButton": false,
            "debug": false,
            "positionClass": "toast-top-center",
            "onclick": null,
            "showDuration": "500",
            "hideDuration": "500",
            "timeOut": "2000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        };

        $("#ddlGroups").bind("change", function () {
            postData.group = this.value;
            xhrRequest(location.href);
        });

        $("#ddlFilter + ul.dropdown-menu input[type='radio']").bind("click", function () {
            postData.active = this.value == "" ? "" : this.value == 1;
            xhrRequest(location.href);
        });

        $("#btnResetCancel").bind("click", function () {
            document.getElementById("resetPasswordForm").reset();
        });

        btnResetPassword.bind("click", function () {
            var _postData = {};
            var uidobjs = $("#tableview").find("input[name='uids']:checked");
            var uids = [];

            uidobjs.each(function () {
                uids.push(this.value);
            });

            if (uids.length == 0) {
                toastr["warning"]("未选择需要重置密码的账号", "用户密码重置");
                return;
            }

            _postData.chkpwd = $("#txtConfirmPwd > input").val();
            _postData.uids = uids.join(",");
            btnResetPassword.empty().append('<i class="fa fa-spinner fa-spin"></i> 重置密码中');
            btnResetPassword.attr("disabled", "disabled");

            $.ajax({
                url: $("#resetPasswordForm").attr("action"),
                type: "POST",
                data: _postData,
                success: function (obj) {
                    btnResetPassword.message(obj, uidobjs);
                },
                error: function () {
                    toastr["error"]("程序碰到问题没有正确执行！", "用户密码重置");
                },
                complete: function () {
                    btnResetPassword.init();
                }
            });
        });

        var btnDeleteConfirm = $("#btnDeleteConfirm");
        var btnDeleteCancel = $("#btnDeleteCancel");

        btnDeleteCancel.bind("click", function () {
            document.getElementById("deleteUsersForm").reset();
        });
        btnDeleteConfirm.init = function () {
            this.empty().html("删除账户");
            this.removeAttr("disabled");
        };
        btnDeleteConfirm.message = function (response, uidobjs) {
            if (response.Result) {
                var uidList = response.Data;
                var errCount = 0;

                if (uidList) {
                    uidobjs.each(function () {
                        for (var i in uidList) {
                            if (uidList[i] == this.value) {
                                if (!this.checked) this.click();
                                errCount++;
                                return;
                            }
                        }

                        if (this.checked) this.click();
                    });
                }

                if (errCount > 0) {
                    toastr["warning"]("部分账户删除失败", "删除账户");
                } else {
                    toastr["success"](response.Message, "删除账户");
                    xhrRequest(location.href);
                }

                btnDeleteCancel.click();
            } else {
                toastr["error"](response.Message, "删除账户");
            }
        };

        btnDeleteConfirm.bind("click", function () {
            var _postData = {};
            var uidobjs = $("#tableview").find("input[name='uids']:checked");
            var uids = [];

            uidobjs.each(function () {
                uids.push(this.value);
            });

            if (uids.length == 0) {
                toastr["warning"]("未选择需要删除的账号", "删除账户");
                return;
            }

            _postData.chkpwd = $("#txtConfirmPwd_Delete > input").val();
            _postData.uids = uids;

            btnDeleteConfirm.empty().append('<i class="fa fa-spinner fa-spin"></i> 账户删除中');
            btnDeleteConfirm.attr("disabled", "disabled");

            $.ajax({
                url: $("#deleteUsersForm").attr("action"),
                type: "POST",
                data: JSON.stringify(_postData),
                contentType: "application/json",
                dataType: "json",
                success: function (obj) {
                    btnDeleteConfirm.message(obj, uidobjs);
                },
                error: function () {
                    toastr["error"]("程序碰到问题没有正确执行！", "用户密码重置");
                },
                complete: function () {
                    btnDeleteConfirm.init();
                }
            });
        });

        var btnAppendCancel = $("#btnAppendCancel");
        var btnAppendToGroup = $("#btnAppendToGroup");
        var appendToForm = $("#appendToForm");
        btnAppendCancel.bind("click", function () {
            document.getElementById("appendToForm").reset();
        });
        btnAppendToGroup.init = function () {
            this.empty().html("添加到组");
            this.removeAttr("disabled");
        };
        btnAppendToGroup.message = function (response) {

        };
        btnAppendToGroup.bind("click", function () {
            var _postData = {};
            var gids = [];
            var uids = [];

            appendToForm
                .find("input[name='atgroups']:checked")
                .each(function () {
                    gids.push(this.value);
                });
            $("#tableview").find("input[name='uids']:checked").each(function () {
                uids.push(this.value);
            });

            _postData.gids = gids;
            _postData.uids = uids;

            btnAppendToGroup.empty().append('<i class="fa fa-spinner fa-spin"></i> 正在执行');
            btnAppendToGroup.attr("disabled", "disabled");

            $.ajax({
                url: appendToForm.attr("action"),
                type: "POST",
                data: JSON.stringify(_postData),
                contentType: "application/json",
                dataType: "json",
                success: function (obj) {
                    if (obj.Result) {
                        toastr["success"](obj.Message, "添加用户到组");
                        xhrRequest(location.href);
                    } else {
                        toastr["error"](obj.Message, "添加用户到组");
                    }
                },
                error: function () {
                    toastr["error"]("程序碰到问题没有正确执行！", "添加用户到组");
                },
                complete: function () {
                    btnAppendToGroup.init();
                }
            });
        });

        btnSearch.bind("click", function () {
            xhrRequest(location.href);
            return false;
        });

        $('.bs-select').selectpicker({
            iconBase: 'fa',
            tickIcon: 'fa-check'
        });

        container
        .delegate("#tableview .group-checkable", "change", function () {
            var set = jQuery(this).attr("data-set");
            var checked = jQuery(this).is(":checked");
            jQuery(set).each(function () {
                if (checked) {
                    $(this).attr("checked", true);
                } else {
                    $(this).attr("checked", false);
                }
            });
            jQuery.uniform.update(set);
        })
        .delegate("ul.pagination li:not(.disabled, .active) > a", "click", function () {
            xhrRequest(this.href);
            return false;
        })
        .delegate("ul.pagination li.disabled > a, ul.pagination li.active > a", "click", function () {
            return false;
        })
        .delegate("td.l-status > a", "click", function () {
            var _self = $(this);
            var text = _self.text();
            var href = _self.attr("href");

            if (text == "等待") return false;

            _self
                .removeClass("label-success label-warning")
                .addClass("label-default");
            _self.html("等待");

            $.ajax({
                url: this.href,
                type: "POST",
                success: function (obj, status, xhr) {
                    _self.removeClass("label-default");

                    if (obj.Result) {
                        toastr["success"](obj.Message, "用户状态修改");
                        if (text == "正常") {
                            _self.addClass("label-warning");
                            _self.html("停用");
                            _self.attr("href", href.replace("&status=false", "&status=true"));
                        } else {
                            _self.addClass("label-success");
                            _self.html("正常");
                            _self.attr("href", href.replace("&status=true", "&status=false"));
                        }
                    } else {
                        toastr["error"](obj.Message, "用户状态修改");
                        _self.addClass(text == "正常" ? "label-success" : "label-warning");
                        _self.html(text);
                        _self.attr("href", href);
                    }
                },
                error: function () {
                    _self.removeClass("label-default");
                    toastr["error"]("程序碰到问题没有正确执行！", "用户状态修改");
                    _self.addClass(text == "正常" ? "label-success" : "label-warning");
                    _self.html(text);
                },
                complete: function () {
                }
            });

            return false;
        });

        // 附加验证方法
        jQuery.validator.addMethod(
            "uidRule",
            function (value, element) {
                return this.optional(element) || !/(^_.*$)|[^_\w\d]/.test(value)
            },
            "UID不合法，不能以下划线开头且只能以字符数字及下划线组成。"
        );

        var validator = addUserForm.validate({
            onsubmit: false,
            rules: {
                uid: {
                    required: true,
                    minlength: 3,
                    maxlength: 15,
                    uidRule: true
                },
                password: {
                    required: true,
                    minlength: 6
                },
                firstname: "required",
                lastname: "required",
                phone: {
                    maxlength: 11
                },
                qq: {
                    digits: true,
                    minlength: 5,
                    maxlength: 11
                },
                email: {
                    required: true,
                    email: true
                }
            },
            messages: {
                uid: {
                    required: "UID必须填写",
                    minlength: "字符不能少于{0}个",
                    maxlength: "字符不能超过{0}个"
                },
                password: {
                    required: "密码不能为空",
                    minlength: "密码长度不符合要求"
                },
                firstname: "姓氏必须填写",
                lastname: "名字必须填写",
                phone: {
                    maxlength: "电话号码长度超过11个字符，将被截断"
                },
                qq: {
                    digits: "请输入正确的QQ号",
                    minlength: "请输入正确的QQ号",
                    maxlength: "请输入正确的QQ号"
                },
                email: {
                    required: "Email必须提供",
                    email: "非法的Email格式"
                }
            },
            errorPlacement: function (error, element) {
                element.closest(".form-group").removeClass("has-success").addClass("has-error");
            },
            success: function (label, element) {
                $(element).closest(".form-group").removeClass("has-error").addClass("has-success");
            }
        });

        btnCreate.bind("click", function () {
            if (!addUserForm.valid()) return false;

            btnCreate.empty().append('<i class="fa fa-spinner fa-spin"></i> 正在创建');
            btnCreate.attr("disabled", "disabled");

            if (fileuoloadData) {
                fileuoloadData.submit();
            } else {
                $.ajax({
                    url: addUserForm.attr("action"),
                    data: addUserForm.serializeArray(),
                    type: "POST",
                    success: function (Response) {
                        btnCreate.message(Response);
                    },
                    error: function () {
                        toastr["error"]("程序碰到问题没有正确执行！", "创建新用户");
                    },
                    complete: function () {
                        btnCreate.init();
                    }
                });
            }

            return false;
        });

        btnCancel.bind("click", function () {
            addUserForm[0].reset();
            addUserForm.Items.each(function () {
                $(this).removeClass("has-success has-error");
            });
            fileuoloadData = null;
            upImgPreview.reset();
        });

        var lb = new LoadingBox("#table_content");
        lb.Text = "数据载入中...";
        function xhrRequest(post_url) {
            postData["like"] = txtLikeName.val();
            lb.Show();

            $.ajax({
                url: post_url,
                data: postData,
                type: "POST",
                success: function (html, txtStatusCode) {
                    container.empty().append(html);
                },
                complete: function () {
                    Metronic.initComponents();
                    lb.Hide();
                }
            });
        }

        var userDetailPanel = $("#user_detail_panel");
        userDetailPanel.Body = $("#user_detail_panel_body");
        userDetailPanel.on("show.bs.modal", function (e) {
            userDetailPanel.Body.empty().append(
                '<img src="/assets/global/img/loading-spinner-grey.gif" alt="" class="loading">' +
				'<span>&nbsp;&nbsp;Loading... </span>');
        });
    }

    return {
        init: function () {
            userList();
        }
    };
} ();